package org.qy.ca.client;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.*;
import java.io.*;
import java.net.URI;
import java.security.KeyStore;
import java.security.SecureRandom;

/**
 * @Description:	des
 * @Author:		方宇康
 * @CreateDate:	2020/5/18 10:35
 * @Version:      	1.0.0.1
 * @Company:       联通智网科技有限公司
 */
public class HttpsTruststoreApacheConnect
{
    /**
     * 客户端证书路径，用了本地绝对路径，需要修改
     */
    private final static String CLIENT_CERT_FILE = "E:\\个人晋升\\CA证书\\client.p12";

    /**
     * 客户端证书密码
     */
    private final static String CLIENT_PWD = "123456";

    /**
     * 信任库路径，即keytool生成的那个自定义名称的库文件
     */
    private final static String TRUST_STRORE_FILE = "D:\\Java\\jdk1.8.0_191\\jre\\lib\\security\\javaclient.truststore";

    /**
     * 信任库密码，即keytool时的密码
     */
    private final static String TRUST_STORE_PWD = "123456";

    public static void httpsCall() throws Exception
    {
        // 初始化密钥库
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = getKeyStore(CLIENT_CERT_FILE, CLIENT_PWD, "PKCS12");
        keyManagerFactory.init(keyStore, CLIENT_PWD.toCharArray());
        // 初始化信任库
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        KeyStore trustkeyStore = getKeyStore(TRUST_STRORE_FILE, TRUST_STORE_PWD, "JKS");
        trustManagerFactory.init(trustkeyStore);
        // 初始化SSL上下文
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
//        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,new String[]{"TLSv1", "TLSv2", "TLSv3"},null,
//                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLContext(sslContext).build();
        HttpGet getCall = new HttpGet();
        getCall.setURI(new URI("https://www.qy-bb.club"));
        CloseableHttpResponse response = closeableHttpClient.execute(getCall);
        System.out.println(convertStreamToString(response.getEntity().getContent()));
    }

    public static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try
        {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                is.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 获得KeyStore
     * 
     * @param keyStorePath
     * @param password
     * @param type
     * @return      
     * @exception   
     * @date        2020/5/18 12:18
     */
    private static KeyStore getKeyStore(String keyStorePath, String password, String type) throws Exception
    {
        FileInputStream is = new FileInputStream(keyStorePath);
        KeyStore ks = KeyStore.getInstance(type);
        ks.load(is, password.toCharArray());
        is.close();
        return ks;
    }

    public static void main(String[] args) throws Exception
    {
        httpsCall();
    }

}
